﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EzDesk.Core.ServiceImpl.Repositories.Interface;
using EzDesk.Core.Model;

namespace EzDesk.Core.ServiceImpl.Repositories
{
    public class PositionRepository:IPositionRepository,IRepository<Position>
    {
        private EzDeskDataContext _db;

        public PositionRepository(EzDeskDataContext db)
        {
            _db = db;
        }

        public PositionRepository()
            : this(new EzDeskDataContext())
        { }

        #region IRepository<Position> Members

        public void SaveChanges()
        {
            _db.SubmitChanges();
        }

        public Guid Add(Position model, bool saveChanges = true)
        {
            var entity = model.ToEntity();
            _db.ez_Positions.InsertOnSubmit(entity);

            if (saveChanges)
            {
                SaveChanges();
            }

            return entity.PosId;
        }

        public Position GetById(Guid id)
        {
            Position position = null;
            if (id != null)
            {
                position = _db.ez_Positions.Where(p => p.PosId == id)
                    .SingleOrDefault()
                    .ToModel();
            }
            return position;
        }

        public IQueryable<Position> GetAll()
        {
            return from position in _db.ez_Positions
                   select new Position()
                   {
                       Id = position.PosId,
                       Priority = position.Priority,
                       Description = position.Description,
                   };
        }

        public void Delete(Guid id, bool saveChanges = true)
        {
            var entity = _db.ez_Positions.Where(p => p.PosId == id)
                .SingleOrDefault();
            _db.ez_Positions.DeleteOnSubmit(entity);

            if (saveChanges)
            {
                SaveChanges();
            }
        }

        public void Update(Position model, bool saveChanges = true)
        {
            var entity = _db.ez_Positions.FirstOrDefault(p => p.PosId == model.Id);
            if (entity != null)
            {
                ModelConvert.CopyValuePosition(entity, model);
            }

            if (saveChanges)
            {
                SaveChanges();
            }

        }
        #endregion
    }
}
